package com.yunquan.ohana.base

import com.yunquan.ohana.utils.FileUtils
import com.yunquan.ohana.utils.L
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter

class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {

    private var defaultHandler: Thread.UncaughtExceptionHandler? = null

    companion object {
        val instance: CrashHandler by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { CrashHandler() }
    }

    fun init() {
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this) // 设置全局异常捕获
    }

    override fun uncaughtException(thread: Thread, ex: Throwable) {
        saveCrashInfoToFile(ex)
        val element = ex.stackTrace[3]
        val mClassName = element.fileName
        val mMethodName = element.methodName
        val mLineNumber = element.lineNumber
        val sb = StringBuffer()
        sb.append("\r\n==============================\r\n")
            .append(mMethodName)
            .append("(")
            .append(mClassName)
            .append(":")
            .append(mLineNumber)
            .append(")")
            .append("\r\n==============================\r\n")
            .append(ex.message)
        val result = sb.toString()
        // 记录日志
        L.e("CrashHandler 未捕获异常: $result")
        // 交给系统默认处理（避免死循环）
        defaultHandler?.uncaughtException(thread, ex)
    }

    private fun saveCrashInfoToFile(ex: Throwable) {
        val crashLog = StringWriter().apply { ex.printStackTrace(PrintWriter(this)) }.toString()
        val file = File(FileUtils.getOtherPath(), "/crash_log.txt")
        file.writeText(crashLog)
    }
}
